package com.tanhua.server.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Value("${tanhua.cache.enable}")
    private Boolean enable;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
       return enable&&methodParameter.hasMethodAnnotation(Cache.class)&&
               methodParameter.hasMethodAnnotation(GetMapping.class);
    }

    @Override
    public Object beforeBodyWrite
            (Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
       if(o==null)
           return null;
       String data="";
       if(o instanceof String)
       {
           data=(String) o;
       }

        try {
            data = MAPPER.writeValueAsString(o);

            String key=RedisCacheInterceptor.createRediskey
                    (((ServletServerHttpRequest)serverHttpRequest).getServletRequest());
            redisTemplate.opsForValue().set(key,data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        return o;
    }
}